/*
 * @lc app=leetcode.cn id=328 lang=cpp
 *
 * [328] 奇偶链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
    void _swap(ListNode *head, ListNode *p, ListNode *q)
    {
        head->next = q;
        p->next = q->next;
        q->next = p;
    }

public:
    ListNode *oddEvenList(ListNode *head)
    {
        if (head == nullptr)
            return nullptr;
        vector<ListNode *> odd, even;
        while (head)
        {
            odd.push_back(head);
            if (head->next)
            {
                even.push_back(head->next);
                head = head->next;
            }
            head = head->next;
        }

        for (int i = 1; i < odd.size(); i++)
        {
            odd[i - 1]->next = odd[i];
        }
        if (even.size())
        {
            (*(odd.end() - 1))->next = even[0];
            for(int i = 1; i < even.size(); i++)
            {
                even[i-1]->next = even[i];
            }
            (*(even.end() - 1))->next = nullptr;
        }

        return odd[0];
    }
};
// @lc code=end
